import React, { useEffect, useState } from "react";
import { Table, Button, message } from "antd";
import { blogList } from '../../api/admin';
import { useNavigate } from 'react-router-dom';

const FileTable = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    blogList()
      .then(res => {
        if (res.code === 200) {
          setData(res.data);
        } else {
          message.error('数据获取失败');
        }
      })
      .catch(() => message.error('网络错误'))
      .finally(() => setLoading(false));
  }, []);

  const navigate = useNavigate();

  const onEdit = (record) => {
    const encodedPath = encodeURIComponent(record.path);
    navigate(`/blog/edit/${encodedPath}`);
  };

  const onDelete = (record) => {
    message.info(`删除: ${record.name}`);
    // 删除逻辑
  };

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "路径",
      dataIndex: "path",
      key: "path",
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (text) => (text === "file" ? "文件" : "文件夹"),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => {
        const isFile = record.type === "file";
        const isEmptyDir =
          record.type === "directory" &&
          (!record.children || record.children.length === 0);

        return (
          <>
            {isFile && (
              <>
                <Button type="link" onClick={() => onEdit(record)}>
                  编辑
                </Button>
                <Button type="link" danger onClick={() => onDelete(record)}>
                  删除
                </Button>
              </>
            )}
            {isEmptyDir && (
              <Button type="link" danger onClick={() => onDelete(record)}>
                删除
              </Button>
            )}
          </>
        );
      },
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="path"
        pagination={false}
        loading={loading}
        expandable={{ childrenColumnName: "children" }}
      />
    </div>
  );
};

export default FileTable;
